import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';
import JSON5 from 'json5';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { addOhPackageDps } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel, CURRENT_HMOS_API,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';
import { mod } from '../../../../src/utils/math-util';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: CURRENT_HMOS_API,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {},
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const commands = '--mode module -p module=entry@ohosTest -p isOhosTest=true -p buildMode=test assembleHap --analyze=normal --parallel'.split(' ');
  // switch to atomic service
  const data = `{
  "app": {
    "bundleName": "com.example.myapplication",
    "bundleType": "atomicService",
    "vendor": "example",
    "versionCode": 1000000,
    "versionName": "1.0.0",
    "icon": "$media:app_icon",
    "label": "$string:app_name"
  }
}
`;
  fse.writeFileSync(path.resolve(projectRootPath, 'AppScope', 'app.json5'), data);

  // write ohosTest module data
  const moduleData = `{
  "module": {
    "name": "entry_test",
    "type": "feature",
    "description": "$string:module_test_desc",
    "mainElement": "TestAbility",
    "deviceTypes": [
      "phone",
      "tablet",
      "2in1"
    ],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": "$profile:test_pages",
    "abilities": [
    ]
  }
}
`;
  fse.writeFileSync(path.resolve(projectRootPath, 'entry', 'src', 'ohosTest', 'module.json5'), moduleData);
  // build hap
  const buildResult = await runHvigorAsync(projectRootPath, commands);
  expect(buildResult.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('DTS2025011717602')
  .description('元服务下运行ohos test不应该检测规则')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.AR).build())
  .testFun(testFun)
  .load();
